package com.wxmit.framework.satoken.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.wxmit.framework.satoken.core.service.StpInterfaceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description sa-token 配置类
 * @Author huangxiong
 * @Date 2022/7/8 17:14
 * @Version V1.0
 */
@Configuration
public class ShushanSaTokenConfiguration implements WebMvcConfigurer {

    @Autowired
    private SecurityProperties securityProperties;
    

    /**
     * 权限
     */
    @Bean
    public StpInterface getStpInterfaceImpl() {
        return new StpInterfaceImpl();
    }


    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 注册 Sa-Token 的路由拦截器
        registry.addInterceptor(new SaInterceptor((handler)->{
            AnnotationExcludeUrlProperties excludeUrlProperties = SpringUtil.getBean(AnnotationExcludeUrlProperties.class);
            // 登录验证 -- 排除多个路径
            SaRouter
                    // 获取所有的
                    .match("/**")
                    // 排除下不需要拦截的
                    .notMatch(securityProperties.getExcludes())
                    .notMatch(excludeUrlProperties.getExcludes())
                    // 对未排除的路径进行检查
                    .check(StpUtil::checkLogin);
        }).isAnnotation(true)).addPathPatterns("/**");
    }

    /**
     * 跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}
